import { EnumBusinessTripType, EnumKnowledgeExtendType, EnumMemberSalaryType, EnumOvertimeType, EnumWelfare, EnumWorkTime, MemberIntentionResult, MemberIntentionStep2Request } from "@/apis/endpoint/model"
import { getMyIntentionstep2GetextendsId, postMyIntentionstep2 } from "@/apis/endpoint/my"
import { validateScheme } from "@/utils/app"
import { useImmer } from "use-immer"
import Taro from '@tarojs/taro'
import { isSetValue } from "@/utils/helper"
import { gcj02tobd09 } from "@/utils/coor-transform"

interface StepTwoState extends Partial<MemberIntentionStep2Request>{
  extendItems?: Array<{
   extendType: EnumKnowledgeExtendType
   extendOptions: string[]
   id: number
   label: string
   values: string[]
  }>
}
export function useStepTwo(next: IFn) {
  const workTimeOptions: IOption<EnumWorkTime>[] = [
    { value: EnumWorkTime.双休, label: "双休" },
    { value: EnumWorkTime.大小周, label: "大小周" },
    { value: EnumWorkTime.单休, label: "单休" },
    { value: EnumWorkTime.早晚轮班, label: "早晚轮班" },
    { value: EnumWorkTime.夜班, label: "夜班" },
  ]
  const overTimeOptions: IOption<EnumOvertimeType>[] = [
    { value: EnumOvertimeType.不接受加班, label: "不接受加班", desc: "没有加班" },
    { value: EnumOvertimeType.偶尔加班, label: "偶尔加班", desc: "<4小时/周" },
    { value: EnumOvertimeType.适度加班, label: "适度加班", desc: "4~8小时/周" },
    { value: EnumOvertimeType.经常加班, label: "经常加班", desc: ">8小时/周" },
  ]
  const outOptions: IOption<EnumBusinessTripType>[] = [
    { value: EnumBusinessTripType.不按受出差, label: "不按受出差", desc: "本地工作" },
    { value: EnumBusinessTripType.偶尔出差, label: "偶尔出差", desc: "<20%时间" },
    { value: EnumBusinessTripType.经常出差, label: "经常出差", desc: "30%~60%时间" },
    { value: EnumBusinessTripType.频繁出差, label: "频繁出差", desc: ">70%时间" },
  ]
  const salaryTypeOptions: IOption<EnumMemberSalaryType>[] = [
    { value: EnumMemberSalaryType.固定薪资, label: "固定薪资" },
    { value: EnumMemberSalaryType.底薪_绩效, label: "底薪_绩效" },
    { value: EnumMemberSalaryType.底薪_绩效_提成, label: "底薪_绩效_提成" },
    { value: EnumMemberSalaryType.薪资_提成, label: "薪资_提成" },
  ]
  const welfareOptions: IOption<EnumWelfare>[] = [
    { value: EnumWelfare.五险一金, label: "五险一金" },
    { value: EnumWelfare.带薪年假, label: "带薪年假" },
    { value: EnumWelfare.餐补, label: "餐补" },
    { value: EnumWelfare.交通补贴, label: "交通补贴" },
    { value: EnumWelfare.住房补贴, label: "住房补贴" },
    { value: EnumWelfare.包吃, label: "包吃" },
    { value: EnumWelfare.包住, label: "包住" },
  ]
  const [stepTwoState, setStepTwoState] = useImmer(getInitialState())
  function getInitialState(): StepTwoState {
    return {
      workTime: [],
      welfare: [],
      extendItems: [],
      address: "",
      lng: 0,
      lat: 0,
      distance: 0
    }
  }
  function getStepTwoOptions(id: number) {
    return getMyIntentionstep2GetextendsId(id).send()
    .then(list => {
      setStepTwoState(draft => {
        const hasValues = draft.extendValues && draft.extendValues.length > 0
        list.forEach(item => {
          const values = hasValues ? draft.extendValues!.find(l => l.id === item.id)?.extendValues ?? [] : []
          draft.extendItems!.push({
            extendType: item.extendType,
            extendOptions: item.extendOptions,
            id: item.id,
            label: item.nameByMember!,
            values
          })
        })
      })
    })
  }
  function receiveStepTwo(setting: MemberIntentionResult) {
    const patchFields: (keyof Omit<StepTwoState, "extendItems">)[] = [
      "address", "basicSalary", "businessTripType", "distance", "lat", "lng", "overtimeType", "periodOfProbation",
      "salaryType", "totalIncome", "welfare", "workTime", "extendValues"
    ]
    let patch: INullable<{[key in keyof Omit<StepTwoState, "extendItems">]: MemberIntentionResult[key]}> = null
    patchFields.forEach(field => {
      if (isSetValue(setting[field])) {
        patch ??= {}
        // @ts-ignore
        patch[field] = setting[field]
      }
    })
    if (patch) {
      setStepTwoState(draft => {
        Object.keys(patch!)
        .forEach(field => {
          draft[field] = patch![field]
        })
      })
    }
  }
  async function chooseAddress() {
    try {
      const {latitude,longitude} = await Taro.getFuzzyLocation({type: "gcj02"})
      const location = await Taro.chooseLocation({latitude,longitude})
      console.log("[chooseAddress]选择地址成功", location)
      if (location.address) {
        const [lng, lat] = gcj02tobd09(location.longitude, location.latitude)
        setStepTwoState(draft => {
          draft.address = location.address
          draft.lat = lat
          draft.lng = lng
        })
      }
    } catch (error) {
      console.log("[chooseAddress]选择地址失败", error)
    }
  }
  async function saveStepTwo() {
    const params = {} as MemberIntentionStep2Request
    const valid = validateScheme(stepTwoState, params, {
      workTime: "workTime",
      periodOfProbation: "periodOfProbation",
      overtimeType: "overtimeType",
      address: "address",
      lng: "lng",
      lat: "lat",
      distance: "distance",
      businessTripType: "businessTripType",
      basicSalary: "basicSalary",
      totalIncome: "totalIncome",
      salaryType: "salaryType",
      welfare: "welfare"
    }, {
      workTime: {
        field: "workTime",
        dataField: "workTime",
        message: "请选择可接受上班时间"
      },
      periodOfProbation: {
        field: "periodOfProbation",
        dataField: "periodOfProbation",
        message: "请选择试用期"
      },
      overtimeType: {
        field: "overtimeType",
        dataField: "overtimeType",
        message: "请选择加班接受度"
      },
      address: {
        field: "address",
        dataField: "address",
        message: "请选择你的住址"
      },
      lng: {
        field: "lng",
        dataField: "lng",
        message: "请选择你的住址"
      },
      lat: {
        field: "lat",
        dataField: "lat",
        message: "请选择你的住址"
      },
      distance: {
        field: "distance",
        dataField: "distance",
        message: "请设置可接受通勤范围"
      },
      businessTripType: {
        field: "businessTripType",
        dataField: "businessTripType",
        message: "请选择出差接受度"
      },
      basicSalary: {
        field: "basicSalary",
        dataField: "basicSalary",
        getValue(value) {
          return Number(value!)
        },
        message: "请输入最低可接受薪资"
      },
      totalIncome: {
        field: "totalIncome",
        dataField: "totalIncome",
        getValue(value) {
          return Number(value!)
        },
        message: "请输入最低期望总收入"
      },
      salaryType: {
        field: "salaryType",
        dataField: "salaryType",
        message: "请选择薪资结构"
      },
      welfare: {
        field: "welfare",
        dataField: "welfare",
        message: "请选择福利"
      },
    })
    if (!valid) return
    if (stepTwoState.extendItems?.length) {
      params.extendValues = stepTwoState.extendItems.map(item => {
        return {
          id: item.id,
          extendValues: item.values
        }
      })
    }
    await postMyIntentionstep2(params).send()
    Taro.showToast({
      icon: "success",
      title: "设置成功"
    })
    next()
  }
  return {
    workTimeOptions,
    overTimeOptions,
    outOptions,
    salaryTypeOptions,
    welfareOptions,
    stepTwoState,
    setStepTwoState,
    getStepTwoOptions,
    saveStepTwo,
    receiveStepTwo,
    chooseAddress
  }
}
